package com.fdb.efp.nls.api.rest;

import com.fdb.basic.framework.core.constant.ApplicationConstance;
import com.fdb.basic.framework.core.constant.DataRuleType;
import com.fdb.basic.framework.core.constant.PubConstant;
import com.fdb.basic.framework.core.constant.ResponseData;
import com.fdb.basic.framework.core.util.StringUtil;
import com.fdb.basic.framework.core.util.TimeUtil;
import com.fdb.basic.framework.web.controller.AbstractController;
import com.fdb.efp.nls.api.service.PartnerInfoFrontService;
import com.fdb.efp.cus.service.facade.PartnerInfoService;
import com.fdb.efp.cus.service.facade.PartnerPrdInfoService;
import com.fdb.efp.cus.service.vo.PartnerInfoVO;
import com.fdb.efp.cus.service.vo.PartnerPrdInfoVO;
import com.fdb.efp.e4a.service.facade.SRoleDataRuleService;
import com.gdrcu.efp.cus.common.CusConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/api")
public class PartnerInfoController extends AbstractController {

	@Autowired
	@Qualifier("partnerInfoService")
	private PartnerInfoService partnerInfoService;

	@Autowired
	private PartnerInfoFrontService partnerInfoFrontService;

	@Autowired
	@Qualifier("partnerPrdInfoService")
	private PartnerPrdInfoService partnerPrdInfoService;

	@Autowired
	@Qualifier("sRoleDataRuleService")
	private SRoleDataRuleService sRoleDataRuleService;


	/**
	 * 列表数据查询
	 * @param vo
	 * @return
	 */
	@RequestMapping(value="/partner/infos", method=RequestMethod.POST)
	public @ResponseBody
	ResponseData<List<PartnerInfoVO>> queryPartnerInfoAll(@RequestBody PartnerInfoVO vo) {
		List<PartnerInfoVO> outputVo = null;
		// 根据用户角色获取用户权限方案
		Map<String, String> dataRuleTypeMap = sRoleDataRuleService.getDataRuleType(httpRequest.getRequestURI(),getUserRoles());
		vo.setPrdCodebyBaseInfo(dataRuleTypeMap == null ? null : dataRuleTypeMap.get(PubConstant.PRD_CODE));
		DataRuleType dataRuleType = DataRuleType.getDataRuleType(dataRuleTypeMap == null ? null : dataRuleTypeMap.get(PubConstant.PERMIS_TYPE));
		setUserInfoToVO(vo);
		// 根据权限方案调用不同的方案进行数据查询
		switch (dataRuleType) {
			case Owner:
				outputVo = partnerInfoService.queryAllOwner(vo);
				break;
			case CurrOrg:
				outputVo = partnerInfoService.queryAllCurrOrg(vo);
				break;
			case CurrDownOrg:
				outputVo = partnerInfoService.queryAllCurrDownOrg(vo);
				break;
			default:
				outputVo = partnerInfoService.queryAllOwner(vo);
				break;
		}
		return getResponseData(outputVo);
	}

	/**
	 * 根据主键查询详情
	 * @return
	 */
	@RequestMapping(value="/partner/info", method=RequestMethod.GET)
	public @ResponseBody ResponseData<PartnerInfoVO> queryByPk() {
		PartnerInfoVO inVo = new PartnerInfoVO();
		PartnerInfoVO outputVo = partnerInfoService.queryByPk(inVo);
		return getResponseData(outputVo);

	}

	/**
	 * 根据主键删除信息
	 * @param inPartnerInfoVo
	 * @return
	 */
	@RequestMapping(value="/partner/info", method=RequestMethod.DELETE)
	public @ResponseBody ResponseData<Integer> deleteByPk(@RequestBody PartnerInfoVO inPartnerInfoVo) {
		int outputVo = partnerInfoService.deleteByPk(inPartnerInfoVo);
		return getResponseData(outputVo);

	}

	/**
	 * 根据主键更新信息
	 * @param inPartnerInfoVo
	 * @return
	 */
	@RequestMapping(value="/partner/info", method=RequestMethod.PUT)
	public @ResponseBody ResponseData<Integer> updateByPk(@RequestBody PartnerInfoVO inPartnerInfoVo) {
		setUserInfoToVO(inPartnerInfoVo );
		PartnerInfoVO tempVo = partnerInfoService.queryBySimName(inPartnerInfoVo);
		PartnerInfoVO tempVoName = partnerInfoService.queryByName(inPartnerInfoVo);
		if(Objects.nonNull(tempVo)) {
			if ((tempVo.getParSimpleName() != null && tempVo.getParSimpleName() != "") && tempVo.getParSimpleName().equals(inPartnerInfoVo.getParSimpleName())) {
				ResponseData<Integer> responseData = new ResponseData<Integer>();
				responseData.setMessage("合作方简称是：【"+tempVo.getParSimpleName()+"】的合作方信息已存在！");
				responseData.setCode(ApplicationConstance.FAILURE);
				responseData.setSuccess(false);
				return responseData;
			}
		} else if (Objects.nonNull(tempVoName)){
			if (tempVoName.getPartnerName().equals(inPartnerInfoVo.getPartnerName())) {
				ResponseData<Integer> responseData = new ResponseData<Integer>();
				responseData.setMessage("合作方名称是：【"+inPartnerInfoVo.getPartnerName()+"】的合作方信息已存在！");
				responseData.setCode(ApplicationConstance.FAILURE);
				responseData.setSuccess(false);
				return responseData;
			}
		}
			inPartnerInfoVo.setLastUpdateUser(inPartnerInfoVo.getLoginUserId());
			inPartnerInfoVo.setLastUpdateTime(TimeUtil.getCurrentDateTime());
			int outputVo = partnerInfoService.updateByPk(inPartnerInfoVo);
			return getResponseData(outputVo);

	}

	/**
	 * 新增数据
	 * @param inPartnerInfoVo
	 * @return
	 */
	@RequestMapping(value="/partner/info", method=RequestMethod.POST)
	public @ResponseBody ResponseData<Integer> insertPartnerInfo(@RequestBody PartnerInfoVO inPartnerInfoVo) {
		setUserInfoToVO(inPartnerInfoVo);
		PartnerInfoVO tempVo = partnerInfoService.queryByIdAndName(inPartnerInfoVo);
		if(Objects.nonNull(tempVo)) {
			if (tempVo.getPartnerId().equals(inPartnerInfoVo.getPartnerId()) ) {
				ResponseData<Integer> responseData = new ResponseData<Integer>();
				responseData.setMessage("合作方编号是：【"+inPartnerInfoVo.getPartnerId()+"】的合作方信息已存在！");
				responseData.setCode(ApplicationConstance.FAILURE);
				responseData.setSuccess(false);
				return responseData;
			} else if (!StringUtil.isNullorBank(tempVo.getParSimpleName()) && tempVo.getParSimpleName().equals(inPartnerInfoVo.getParSimpleName())) {
                ResponseData<Integer> responseData = new ResponseData<Integer>();
                responseData.setMessage("合作方简称是：【"+inPartnerInfoVo.getParSimpleName()+"】的合作方信息已存在！");
                responseData.setCode(ApplicationConstance.FAILURE);
                responseData.setSuccess(false);
                return responseData;
			} else if (tempVo.getPartnerName().equals(inPartnerInfoVo.getPartnerName())) {
                ResponseData<Integer> responseData = new ResponseData<Integer>();
                responseData.setMessage("合作方名称是：【"+inPartnerInfoVo.getPartnerName()+"】的合作方信息已存在！");
                responseData.setCode(ApplicationConstance.FAILURE);
                responseData.setSuccess(false);
                return responseData;
			}
		}
		inPartnerInfoVo.setOrgCode(inPartnerInfoVo.getLoginUserOrgCode());
		inPartnerInfoVo.setCreateUser(inPartnerInfoVo.getLoginUserId());
		inPartnerInfoVo.setCreateTime(TimeUtil.getCurrentDateTime());
		int outputVo = partnerInfoService.insertPartnerInfo(inPartnerInfoVo);
		return getResponseData(outputVo);

	}


	/**
	 * 获取不良贷款率
	 * @param vo
	 * @return
	 */
	@RequestMapping(value="/get/bad/loan/ratio", method=RequestMethod.POST)
	public @ResponseBody ResponseData<Double> queryBadLoanRatio(@RequestBody PartnerInfoVO vo) {
		BigDecimal output = BigDecimal.ZERO;
		String partnerId = vo.getPartnerId();
		if(StringUtil.isNullorBank(partnerId)){
			return getResponseData(-1.00);
		}
		//获取合作方关联产品信息
		List<PartnerPrdInfoVO> partnerPrdInfoVOList = this.getPartnerPrdInfos(partnerId);
		if(Objects.nonNull(partnerPrdInfoVOList) && !partnerPrdInfoVOList.isEmpty()){
			//获取产品编号集
			List<String> prdIds = partnerPrdInfoVOList.stream().map(PartnerPrdInfoVO::getPrdId).collect(Collectors.toList());
			if(Objects.isNull(prdIds) || prdIds.isEmpty()){
				return getResponseData(-1.00);
			}
			//获取不良贷款余额
			BigDecimal allBadLoanBalance = partnerInfoFrontService.getBadLoanBalance(prdIds);
			if(BigDecimal.ZERO == allBadLoanBalance){
				return getResponseData(0.00);
			}
			//获取总贷款余额
			BigDecimal allLoanBalance = partnerInfoFrontService.getAllLoanBalance(prdIds);
			if(allLoanBalance == BigDecimal.ZERO){
				return getResponseData(-1.00);
			}
			output = allBadLoanBalance.divide(allLoanBalance, 6, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100"));
		}else{
			return getResponseData(-1.00);
		}
		return getResponseData(output.doubleValue());
	}


	/**
	 * 获取费用结算
	 * @param vo
	 * @return
	 */
	@RequestMapping(value="/get/cost/fee", method=RequestMethod.POST)
	public @ResponseBody ResponseData<Double> queryCostFee(@RequestBody PartnerInfoVO vo) {
		BigDecimal output = BigDecimal.ZERO;
		List<String> prdIds = new ArrayList<>();

		if(StringUtil.isStrNotEmpty(vo.getCostType())){
			String partnerId = vo.getPartnerId();
			if(StringUtil.isNullorBank(partnerId)){
				return getResponseData(0.00);
			}
			//获取合作方关联产品信息
			List<PartnerPrdInfoVO> partnerPrdInfoVOList = this.getPartnerPrdInfos(partnerId);
			if(Objects.nonNull(partnerPrdInfoVOList) && !partnerPrdInfoVOList.isEmpty()){
				//获取产品编号集
				prdIds = partnerPrdInfoVOList.stream().map(PartnerPrdInfoVO::getPrdId).collect(Collectors.toList());
				if(Objects.isNull(prdIds) || prdIds.isEmpty()){
					return getResponseData(0.00);
				}
			}else{
				return getResponseData(0.00);
			}
		}
		//费用类型 = 【放款金额】
		if(CusConstant.COST_TYPE_1.equals(vo.getCostType())){
			BigDecimal loanLmtSetlRatio = vo.getLoanLmtSetlRatio();
			if(null== loanLmtSetlRatio || BigDecimal.ZERO == loanLmtSetlRatio){
				return getResponseData(0.00);
			}else{
				//获取放款总金额
				BigDecimal amountOfLoan = partnerInfoFrontService.getAmountOfLoan(prdIds);
				output = amountOfLoan.multiply(loanLmtSetlRatio).divide(new BigDecimal("100"));
			}
		}
		//费用类型 = 【贷款余额】
		if(CusConstant.COST_TYPE_2.equals(vo.getCostType())){
			BigDecimal loanBalSetlRatio = vo.getLoanBalSetlRatio();
			if(null==loanBalSetlRatio || BigDecimal.ZERO == loanBalSetlRatio){
				return getResponseData(0.00);
			}else{
				//获取总贷款余额
				BigDecimal allLoanBalance = partnerInfoFrontService.getAllLoanBalance(prdIds);
				output = allLoanBalance.multiply(loanBalSetlRatio).divide(new BigDecimal("100"));
			}
		}
		return getResponseData(output.doubleValue());
	}

	/**
	 * 获取合作方信息
	 * @param partnerId 合作方编号
	 * @return
	 */
	private List<PartnerPrdInfoVO> getPartnerPrdInfos(String partnerId){
		PartnerPrdInfoVO partnerPrdInfoVO = new PartnerPrdInfoVO();
		partnerPrdInfoVO.setPartnerId(partnerId);
		return partnerPrdInfoService.queryAllByConditions(partnerPrdInfoVO);
	}


}
